package net.chasing.androidbaseconfig.util;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 防抖动连续点击的辅助类
 * 每个类都包含自己一个OneClickUtil，
 * 避免mLastClickTimeMap包含太多不必要的数据，
 * 同时避免两个类的methodName相同
 */
public class OneClickUtil {
    private static final int MIN_CLICK_DELAY_TIME = 800;

    private final Map<String, Long> mLastClickTimeMap;

    public OneClickUtil() {
        mLastClickTimeMap = new HashMap<>();
    }

    /**
     * 检测是否连续单击了两次
     *
     * @param id 控件id，R文件内控件id都是唯一的
     * @return true为短时间内连续单击两次，false不是
     */
    public boolean check(int id) {
        return check(String.valueOf(id));
    }

    //singleSign能代表唯一标识即可
    public boolean check(String singleSign) {
        return check(singleSign, MIN_CLICK_DELAY_TIME);
    }

    public boolean check(String singleSign, long delayTime) {
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (!mLastClickTimeMap.containsKey(singleSign)) {
            mLastClickTimeMap.put(singleSign, currentTime);
            return false;
        } else {
            Long preTime = mLastClickTimeMap.get(singleSign);
            if (preTime != null) {
                if (currentTime - preTime > delayTime) {
                    mLastClickTimeMap.put(singleSign, currentTime);
                    return false;
                } else {
                    return true;
                }
            } else
                return false;
        }
    }
}
